package org.ruoyi.aibox.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.ruoyi.aibox.domain.AuditTask;
import org.ruoyi.aibox.mapper.AuditTaskMapper;
import org.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 文档审核调度器
 * 负责定时扫描待处理的审核任务，并提交到执行器处理
 */
@Slf4j
@Component
@EnableScheduling
public class DocumentAuditScheduler {

    @Autowired
    private AuditTaskMapper taskMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private DocumentAuditExecutor executor;

    @Autowired
    private AuditTaskCounter taskCounter;

    /**
     * 当前正在处理的任务数
     */
    private final AtomicInteger processingCount = new AtomicInteger(0);

    /**
     * 每1分钟扫描一次待处理任务
     */
    @Scheduled(fixedRate = 60000)
    public void scanPendingTasks() {
        try {
            // 1. 获取系统配置的最大并发数
            int maxConcurrent = Integer.parseInt(configService.selectConfigByKey("sys.audit.max.concurrent"));
            
            // 2. 计算可以处理的任务数
            int available = maxConcurrent - taskCounter.getProcessingCount();
            if (available <= 0) {
                log.debug("当前正在处理的任务数已达到最大并发数: {}", maxConcurrent);
                return;
            }

            // 3. 检查执行器是否可以接受新任务
            if (!executor.canAcceptNewTask()) {
                log.debug("执行器队列已满，暂停提交新任务");
                return;
            }

            // 4. 查询待处理的任务
            List<AuditTask> pendingTasks = taskMapper.selectPendingTasks(available);
            if (pendingTasks.isEmpty()) {
                log.debug("没有待处理的任务");
                return;
            }

            // 5. 提交任务到执行器
            for (AuditTask task : pendingTasks) {
                try {
                    taskCounter.incrementProcessingCount();
                    executor.executeAudit(task.getTaskId());
                    log.info("成功提交审核任务: {}", task.getTaskId());
                } catch (Exception e) {
                    taskCounter.decrementProcessingCount();
                    log.error("提交审核任务失败: {}", task.getTaskId(), e);
                }
            }

        } catch (Exception e) {
            log.error("扫描待处理任务异常", e);
        }
    }

    /**
     * 任务完成时调用此方法减少计数
     */
    public void decrementProcessingCount() {
        processingCount.decrementAndGet();
    }

    /**
     * 获取当前正在处理的任务数
     */
    public int getProcessingCount() {
        return processingCount.get();
    }
} 